<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class StoreCoupon extends Model
{
    use HasFactory;

    protected $guarded = [];
    protected $table = 'store_coupon';

    /**
     * szk
     * 优惠券添加
     * @discountData 增加优惠卷需要的数据
     * @param $discountData
     * @return mixed
     */
    public static function create($discountData)
    {
        $discountData['add_time'] = strtotime(date('Y-m-d H:i:s'));
        $discountData['is_del'] = 0;
        return self::insertGetId($discountData);
    }

    /**
     * szk
     * 优惠券搜索
     * @param $where
     * @return mixed
     */
    public static function search($where)
    {
        return self::with('getStoreCoupon')->where($where)->where('is_del',0)->paginate(5);
    }

    /**
     * szk
     * 优惠券删除
     * @param $id
     * @return mixed
     */
    public static function discountDeleted($id)
    {
        return self::where('id', $id)->update(['is_del'=>1]);
    }

    /**
     * szk
     * 优惠券修改
     * @param $data
     * @param $id
     * @return mixed
     */
    public static function modification($data, $id)
    {
        $data['add_time'] = strtotime($data['add_time']);
        return self::where('id', $id)->update($data);
    }

    /**
     * szk
     * 优惠券详情
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function readStoreCouponRead($id)
    {
        return self::with('getStoreCoupon')->where("id", $id)->first();
    }

    /**
     * szk
     * 模型关联
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function getStoreCoupon()
    {
        return $this->hasOne(StoreCouponIssue::class, 'cid', 'id');
    }

    /**
     * szk
     * 时间改变获取器
     * @param $value
     * @return false|string
     */
    public function getAddTimeAttribute($value)
    {
        return date('Y-m-d H:i:s', $value);
    }

    /**
     * 类型改变
     * @param $value
     * @return string
     */
    public function getTypeAttribute($value)
    {
        if ($value == 0) {
            return "通用卷";
        }
        if ($value == 1) {
            return "品类券";
        }
        if ($value == 2) {
            return "商品券";
        }
    }

    /**
     * 即点即改
     * @param $id
     * @param $status
     * @return int
     */
    public static function changeStatus($id, $status)
    {
        if ($status == 1) {
            self::where('id', $id)->update(['status' => 0]);
            return 0;
        }
        self::where('id', $id)->update(['status' => 1]);
        return 1;
    }

    /**
     * 获取商品的优惠券
     * @param $id
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public static function getProductDiscount($id)
    {
        return self::with('getStoreCoupon')->where('product_id', $id)->where('is_del', 0)->where('status', 1)->get();
    }

}
